<template>
  <el-card class="w-full">
    <div class="main h-[calc(100%-29px)]">
      <div class="w-full">
        <div v-if="queryShow" class="mb-[10px] w-full search-form">
          <el-form :inline="true" :model="queryForm.data" label-width="0px">
            <el-form-item>
              <el-input
                v-model="queryForm.data.blurry"
                clearable
                placeholder="输入任务名称搜索"
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryForm.data.createTime"
                type="datetimerange"
                range-separator=":"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item class="ml-[10px]">
              <el-button type="primary" :icon="Search" @click="search"
                >搜索</el-button
              >
              <el-button :icon="RefreshLeft" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="w-full">
          <div class="w-full flex justify-between">
            <div class="buttons flex align-center">
              <el-button type="primary" :icon="Plus" @click="addMenu"
                >新增</el-button
              >
              <el-button
                type="success"
                :icon="Edit"
                :disabled="!(multipleSelection.length === 1)"
                @click="editSelect"
                >修改</el-button
              >
              <el-button
                type="danger"
                :icon="Delete"
                :disabled="!multipleSelection.length"
                @click="delSelect"
                >删除</el-button
              >
              <el-button type="warning" :icon="Download" @click="exportData"
                >导出</el-button
              >
              <el-button type="info" :icon="Document" @click="showLog"
                >日志</el-button
              >
            </div>
            <div class="settings">
              <el-button-group class="ml-4">
                <el-button
                  type="primary"
                  :icon="Search"
                  @click="queryShow = !queryShow"
                />
                <el-button
                  type="primary"
                  :icon="RefreshLeft"
                  @click="getList"
                />
                <el-popover placement="bottom" :width="200" trigger="click">
                  <template #reference>
                    <el-button type="primary" :icon="Grid" />
                  </template>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <el-checkbox-group
                    v-model="checkedCities"
                    class="columns-show-group"
                    @change="handleCheckedCitiesChange"
                  >
                    <el-checkbox
                      v-for="item in defaultColums.data"
                      :key="item.prop"
                      :label="item.prop"
                      >{{ item.label }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-popover>
              </el-button-group>
            </div>
          </div>
          <div class="flex">
            <div class="role w-full">
              <div v-loading="loading" class="w-full mt-[10px]">
                <el-table
                  ref="multipleTableRef"
                  :data="tableData.data"
                  style="width: 100%"
                  row-key="id"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column
                    v-for="item in colums.data"
                    :key="item.prop"
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width"
                  >
                    <template v-if="item.prop === 'isPause'" #default="scope">
                      <el-tag
                        :type="scope.row.isPause ? 'warning' : 'success'"
                        >{{ scope.row.isPause ? "已暂停" : "运行中" }}</el-tag
                      >
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="200px">
                    <template #default="scope">
                      <el-button
                        v-permission="['admin', 'timing:edit']"
                        size="mini"
                        type="text"
                        @click="editRow(scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        v-permission="['admin', 'timing:edit']"
                        type="text"
                        size="mini"
                        @click="execute(scope.row.id)"
                        >执行</el-button
                      >
                      <el-button
                        v-permission="['admin', 'timing:edit']"
                        type="text"
                        size="mini"
                        @click="
                          updateStatus(
                            scope.row.id,
                            scope.row.isPause ? '恢复' : '暂停'
                          )
                        "
                      >
                        {{ scope.row.isPause ? "恢复" : "暂停" }}
                      </el-button>
                      <el-popconfirm
                        v-permission="['admin', 'timing:del']"
                        width="200px"
                        title="确定停止并删除该任务吗？"
                        @confirm="delConfirm(scope.row)"
                      >
                        <template #reference>
                          <el-button type="text" size="mini">删除</el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="page w-full mt-[10px]">
                <el-pagination
                  v-model:current-page="pageObj.data.currentPage"
                  v-model:page-size="pageObj.data.pageSize"
                  :page-sizes="[10, 20, 30, 40, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pageObj.data.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-dialog
        v-model="addDialog"
        :close-on-click-modal="false"
        :before-close="beforeClose"
        :title="title"
        width="880px"
      >
        <el-form
          ref="formRef"
          :model="form.data"
          :rules="form.rules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务名称" prop="jobName">
                <el-input v-model="form.data.jobName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务描述" prop="description">
                <el-input v-model="form.data.description" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Bean名称" prop="beanName">
                <el-input v-model="form.data.beanName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行方法" prop="methodName">
                <el-input v-model="form.data.methodName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Cron表达式" prop="cronExpression">
                <el-input v-model="form.data.cronExpression" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="子任务ID">
                <el-input
                  v-model="form.data.subTask"
                  placeholder="多个用逗号隔开，按顺序执行"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务负责人" prop="personInCharge">
                <el-input v-model="form.data.personInCharge" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="告警邮箱" prop="email">
                <el-input
                  v-model="form.data.email"
                  placeholder="多个邮箱用逗号隔开"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="失败后暂停">
                <el-radio-group v-model="form.data.pauseAfterFailure">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务状态">
                <el-radio-group v-model="form.data.isPause">
                  <el-radio :label="false">启用</el-radio>
                  <el-radio :label="true">暂停</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="参数内容">
                <el-input v-model="form.data.params" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
      <log-view ref="logView" />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import LogView from "./log.vue";
import {
  Delete,
  Download,
  Edit,
  Grid,
  Plus,
  RefreshLeft,
  Search,
  Document
} from "@element-plus/icons-vue";
import { ElForm, ElMessageBox, ElNotification, ElTable } from "element-plus";
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  getCurrentLevel,
  getJobsList,
  ResultJobs,
  exportJobsList,
  delJobsListApi,
  addJobsListApi,
  editJobsListApi,
  execution,
  updateIsPause
} from "@/api/system";
import { cloneDeep } from "@pureadmin/utils";
import { downloadFile } from "@/utils";
const emits = defineEmits(["setRowObj"]);
const queryShow = ref(true);
const queryForm = reactive({
  data: {
    blurry: undefined,
    createTime: []
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined,
    createTime: []
  };
};
const logView = ref<InstanceType<typeof LogView>>();
const showLog = () => {
  logView.value.addDialog = true;
};
const search = async () => {
  pageObj.data.currentPage = 1;
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const getList = async () => {
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const exportData = async () => {
  let res = await exportJobsList({
    current: pageObj.data.currentPage,
    size: pageObj.data.pageSize,
    sort: "id,desc",
    jobName: queryForm.data.blurry ? queryForm.data.blurry : undefined,
    createTime: queryForm.data.createTime.length
      ? queryForm.data.createTime
      : undefined
  });
  downloadFile(res, "任务数据", "xlsx");
};
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  getList();
};
const getData = () => {
  loading.value = true;
  return new Promise<ResultJobs>(async (resolve, reject) => {
    let data = await getJobsList({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      sort: "id,desc",
      jobName: queryForm.data.blurry ? queryForm.data.blurry : undefined,
      createTime: queryForm.data.createTime.length
        ? queryForm.data.createTime
        : undefined
    });
    loading.value = false;
    resolve(data);
  });
};
const currentLevel = ref(3);
const init = async () => {
  const { level } = await getCurrentLevel();
  currentLevel.value = level;
};
init();
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "任务ID",
      prop: "id",
      width: "80px"
    },
    {
      label: "任务名称",
      prop: "jobName"
    },
    {
      label: "Bean名称",
      prop: "beanName"
    },
    {
      label: "执行方法",
      prop: "methodName"
    },
    {
      label: "参数",
      prop: "params"
    },
    {
      label: "cron表达式",
      prop: "cronExpression"
    },
    {
      label: "状态",
      prop: "isPause"
    },
    {
      label: "描述",
      prop: "description"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "任务ID",
      prop: "id",
      width: "80px"
    },
    {
      label: "任务名称",
      prop: "jobName"
    },
    {
      label: "Bean名称",
      prop: "beanName"
    },
    {
      label: "执行方法",
      prop: "methodName"
    },
    {
      label: "参数",
      prop: "params"
    },
    {
      label: "cron表达式",
      prop: "cronExpression"
    },
    {
      label: "状态",
      prop: "isPause"
    },
    {
      label: "描述",
      prop: "description"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const loading = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref([]);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  search();
  checkedCities.value = colums.data.map(item => item.prop);
});
const form = reactive({
  data: {
    id: null,
    jobName: null,
    subTask: null,
    beanName: null,
    methodName: null,
    params: null,
    cronExpression: null,
    pauseAfterFailure: true,
    isPause: false,
    personInCharge: null,
    email: null,
    description: null
  },
  rules: {
    jobName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
    description: [
      { required: true, message: "请输入任务描述", trigger: "blur" }
    ],
    beanName: [{ required: true, message: "请输入Bean名称", trigger: "blur" }],
    methodName: [
      { required: true, message: "请输入方法名称", trigger: "blur" }
    ],
    cronExpression: [
      { required: true, message: "请输入Cron表达式", trigger: "blur" }
    ],
    personInCharge: [
      { required: true, message: "请输入负责人名称", trigger: "blur" }
    ]
  }
});
const addDialog = ref(false);
const title = ref("新增任务");
const status = ref("add");
const addMenu = () => {
  addDialog.value = true;
  title.value = "新增任务";
  status.value = "add";
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const editRow = async row => {
  addDialog.value = true;
  title.value = "编辑任务";
  status.value = "edit";
  let data = cloneDeep(row);
  form.data = data;
};
const delSelect = () => {
  if (multipleSelection.value.length) {
    ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}条数据?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(async () => {
      await delJobsListApi(multipleSelection.value.map(i => i.id));
      ElNotification({
        title: "系统提示",
        message: "删除成功",
        type: "success"
      });
      search();
    });
  }
};
const editSelect = () => {
  if (multipleSelection.value.length === 1) {
    editRow(multipleSelection.value[0]);
  }
};
const formRef = ref<InstanceType<typeof ElForm>>();
const resetForm = () => {
  form.data = {
    id: null,
    jobName: null,
    subTask: null,
    beanName: null,
    methodName: null,
    params: null,
    cronExpression: null,
    pauseAfterFailure: true,
    isPause: false,
    personInCharge: null,
    email: null,
    description: null
  };
  nextTick(() => {
    formRef.value.resetFields();
  });
};
const beforeClose = d => {
  form.data = {
    id: null,
    jobName: null,
    subTask: null,
    beanName: null,
    methodName: null,
    params: null,
    cronExpression: null,
    pauseAfterFailure: true,
    isPause: false,
    personInCharge: null,
    email: null,
    description: null
  };
  nextTick(() => {
    d();
  });
};
const cancel = () => {
  form.data = {
    id: null,
    jobName: null,
    subTask: null,
    beanName: null,
    methodName: null,
    params: null,
    cronExpression: null,
    pauseAfterFailure: true,
    isPause: false,
    personInCharge: null,
    email: null,
    description: null
  };
  formRef.value.resetFields();
  nextTick(() => {
    addDialog.value = false;
  });
};
const submit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data = cloneDeep(form.data);
      if (status.value === "add") {
        await addJobsListApi(data);
        ElNotification({
          title: "系统提示",
          message: "任务创建成功",
          type: "success"
        });
      } else {
        await editJobsListApi(data);
        ElNotification({
          title: "系统提示",
          message: "任务编辑成功",
          type: "success"
        });
      }
      resetForm();
      nextTick(() => {
        addDialog.value = false;
        search();
      });
    }
  });
};
const delConfirm = async row => {
  await delJobsListApi([row.id]);
  ElNotification({
    title: "系统提示",
    message: "删除成功",
    type: "success"
  });
  search();
};
// 执行
const execute = id => {
  execution(id)
    .then(res => {
      ElNotification({
        title: "系统提示",
        message: "执行成功",
        type: "success"
      });
    })
    .catch(err => {
      console.log(err.response.data.message);
    });
};
// 改变状态
const updateStatus = (id, status) => {
  updateIsPause(id)
    .then(res => {
      ElNotification({
        title: "系统提示",
        message: status + "成功",
        type: "success"
      });
      search();
    })
    .catch(err => {
      console.log(err.response.data.message);
    });
};
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  //margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}

:deep(.el-card__body) {
  width: 100%;
}
</style>
